package com.weme.live.activity.liveview

import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.makeramen.roundedimageview.RoundedImageView
import com.weme.common.util.*
import com.weme.live.R
import com.weme.live.activity.LiveRoomActivity
import com.weme.live.databinding.ViewLiveRoomImListBinding
import com.weme.live.viewmode.LiveViewMode
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.collections.ArrayDeque

data class Message(
    val avatarUrl: String?="",
    val nickname: String,
    val content: String,
    val isOwnMessage: Boolean,
    val translatedContent: String = "",
    val type: Int = 1 // 2 for gift message

)

class LiveRoomImListView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyle: Int = 0
) : FrameLayout(context, attributeSet, defStyle) {

    private val viewBinding = ViewLiveRoomImListBinding.inflate(LayoutInflater.from(context), this, true)
    private var viewModel: LiveViewMode? = null
    private var timerHandler: Handler? = Handler(Looper.getMainLooper())
    private var maxWidth = dp2px(126f)

    private val listTextView: Queue<TextView> = ConcurrentLinkedQueue()
    private val listView: Queue<View> = ConcurrentLinkedQueue()
    private val liveRoomAdapter = object : BaseQuickAdapter<Message, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: Message?) {
            val tvContent = holder.getView<TextView>(R.id.tvContent)
            val tvGiftName = holder.getView<TextView>(R.id.tvGiftName)
            val vFyx = holder.getView<View>(R.id.vFyx)
            val tvFy = holder.getView<TextView>(R.id.tvFy)
            val rimHead = holder.getView<RoundedImageView>(R.id.rimHead)

            tvContent.maxWidth = maxWidth
            tvGiftName.gone()
            vFyx.gone()
            tvFy.gone()

            item?.let {
                when (it.type) {
                    1 -> { // Regular message
                        tvContent.text = it.content
                        tvContent.setTextColor(Color.WHITE)
                        if (it.translatedContent.isNotEmpty()) {
                            vFyx.visible()
                            tvFy.visible()
                            tvFy.text = it.translatedContent
                        }else{
                            listTextView.add(tvFy)
                            listView.add(vFyx)
                        }
                    }
                    2 -> { // Gift message
                        tvGiftName.visible()
                        tvGiftName.text = "[${it.content}]"
                        tvContent.text = context.getString(com.example.resources.R.string.live_im_give_gift)
                        tvContent.setTextColor(Color.parseColor("#FAFF0D"))
                    }
                }

                if (it.isOwnMessage) {
                    val headPic = UserMKHelper.decodeString(UserMKHelper.decodeString(AppMkHelper.HEADPIC))
                    if (!TextUtils.isEmpty(headPic)) {
                        rimHead.loadImage(headPic)
                    } else {
                        rimHead.setImageResource(com.example.resources.R.mipmap.avatar_placeholder)
                    }
                } else {
                    viewModel?.apply {
                        rimHead.loadImage(this.anchorUser?.headPic)
                    } ?: run {
                        rimHead.loadImage(it.avatarUrl)
                    }

                }
            }
        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_live_room_chat, parent)
        }
    }

    init {
        val activity = context as LiveRoomActivity
        viewBinding.rcvList.setVerticalLayoutManager()
        viewBinding.rcvList.adapter = liveRoomAdapter
        viewModel = ViewModelProvider(activity)[LiveViewMode::class.java]

        viewBinding.rcvList.post {
            maxWidth = viewBinding.rcvList.width - 80.dpToPx(context)
        }
        viewModel?.apply {
            sendMsgContentLiveData.observe(activity) {
                addChatMsgList(it)
            }

            addMsgContentLiveData.observe(activity) {
                addChatMsgList(it)
            }
            translateMsgContentLiveData.observe(activity){
                if (listTextView.isNotEmpty() && listView.isNotEmpty()) {
                    listTextView.poll()?.apply {
                        visible()
                        text = it
                    }
                    listView.poll()?.visible()
                    viewBinding.rcvList.postDelayed({
                        viewBinding.rcvList.scrollToBottom()
                    },200)
                }

            }
        }



        startTimer()
    }

    private fun resetTimer() {
        timerHandler?.removeCallbacksAndMessages(null)
        startTimer()
    }

    private fun startTimer() {
        timerHandler?.postDelayed({
            viewBinding.rcvList.fadeOut()
        }, 20 * 1000) // 20 seconds timer
    }

    private fun addChatMsgList(msg: Message) {
        resetTimer()
        liveRoomAdapter.add(msg)
        if (liveRoomAdapter.items.size > 4) {
            liveRoomAdapter.removeAt(0)
        }
        (viewBinding.rcvList.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
            liveRoomAdapter.itemCount - 1, Int.MIN_VALUE
        )
        viewBinding.rcvList.alpha = 1f
    }
}
